<?php
/* 
* @Title:  [前台登陆&注册控制器]
* @Author: {chenlei} [chenleib5@126.com]
* @Date:   2014-04-13 15:47:24
* @Last Modified by:   Administrator
* @Last Modified time: 2014-04-29 08:42:20
* @Copyright:  [hn7m.com]
*/
class LogRegControl extends CommonControl{
	private $model=NULL;
	/**
	 * [__init 自动加载模型]
	 * @return [type] [description]
	 */
	public function __init(){
		parent::__init();
		$this->model=K('User');
	}
	/**
	 * [register 注册]
	 * @return [type] [description]
	 */
	public function register(){
		if(IS_POST){
			//必须同意了用户协议才能让他注册!
			$agree=Q('post.agree',0,'intval');
			if ($agree!=1) {
				$this->error('你傻啊,不知道同意守则啊!');
			}
			if(!$this->model->create()){
				$this->error($this->model->error);
			}
			$uid=$this->model->add_user();
			if(!$uid){
				$this->error('注册失败!');
			}
			//写入session
			session('uid',$uid);
			session('username',Q('post.uaccount'));
			session('go_url','__ROOT__');
			$this->success('恭喜您,注册成功!',U('Index/index'));
		}
		$this->display();
	}
	/**
	 * [ajax_check_user ajax检测用户名是否存在]
	 * @return [type] [description]
	 */
	public function ajax_check_user(){
		if(!IS_AJAX) halt('非法请求!');
		if(K('User')->check_user(Q('post.uaccount','','htmlspecialchars')) or K('Admin')->check_admin(Q('post.uaccount','','htmlspecialchars'))) $this->ajax(0);
		$this->ajax(1);
	}
	/**
	 * [ajax_check_email ajax检测用户注册邮箱是否存在]
	 * @return [type] [description]
	 */
	public function ajax_check_email(){
		if(!IS_AJAX) halt('非法请求!');
		if(K('User')->check_email(Q('post.uemail','','htmlspecialchars'))) $this->ajax(0);
		$this->ajax(1);
	}
	/**
	 * [logout 退出登录]
	 * @return [type] [description]
	 */
	public function logout(){
		if(IS_AJAX){
			session('uid',null);
			session('username',null);
			session('cart',null);
			$return=array(
				'state'		=>1,
				'message'	=>'退出成功!',
				'timeout'	=>2
				);
			$this->ajax($return);
		}
	}
	/**
	 * [login 登录]
	 * @return [type] [description]
	 */
	public function login(){
		if(IS_AJAX){
			if ($user=$this->model->login_user()) {
				$auto=Q('autoLogin',0,'intval');
				if($auto == 1){
					setcookie(session_name(),session_id(),C('COOKIE_EXPIRE'),'/');
				}
				session('uid',$user['uid']);
				session('username',$user['uaccount']);
				$uid=session('uid');
				session('go_url','__ROOT__');
				//登陆时,判断是否存在购物车session
				if(!isset($_SESSION['cart'])){
					$this->cart_to_session($uid);  //如果不存在,将购物车表中的数据压到session
				}else{
					$this->session_to_cart($uid);	//如果存在,将session数据压到数据库表中
				}
				$return=array(
					'state'		=>1,
					'message'	=>'恭喜您,登陆成功!',
					'timeout'	=>3
					);
			}else{
				$return = array(
					'state' => 0,
					'message' => $this->model->error,
					'timeout'=>3
				);
			}
			$this->ajax($return);
		}
		$this->display();
	}
	/**
	 * [code 生成验证码]
	 * @return [type] [description]
	 */
	public function code(){
		$code=new Code();
		$code->show();
	}
}
?>